class FolderContent < ActiveRecord::Base
  belongs_to(:folder,:order => "seq")
  belongs_to(:sub_folder, :foreign_key => "sub_folder_id", :class_name => "Folder",:order => "seq")
  belongs_to(:function,:order => "seq")
  belongs_to(:page,:order => "seq")

  class << self
    include Utils::Text

    def get_next_seq(f_id)
      f_id = Folder.find(:first, :conditions => "top_level is true").id  if empty_or_nil?(f_id)
      sql = "SELECT max(seq) from #{table_name} where folder_id=#{f_id}"
      rslt = connection.query(sql)
      return 1 if rslt[0][0].nil?
      rslt[0][0].to_i + 1
    end

    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    # All methods yield element if block_given otherwise will
    # return results
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    def top_level_folders 
      tl = Folder.find(:first, :conditions => "top_level is true")
      if block_given?
        tl.sub_folder.each{|sf| yield sf}
      else
        tl.sub_folder.dup
      end
    end

    def sub_level_folders 
      contents = find_by_sql("select * from folder_contents where sub_folder_id is not null")
      sub_folders = contents.collect{|c| c.sub_folder}
      if block_given?
        sub_folders.each{|sf| yield sf}
      else
        sub_folders
      end
    end

    def sub_level_folders_for(folder_id)
      contents = find_by_sql("select * from folder_contents where folder_id = #{folder_id} and sub_folder_id is not null")
      sub_folders = contents.collect{|c| c.sub_folder}
      if block_given?
        sub_folders.each{|sf| yield sf}
      else
        sub_folders
      end
    end

    def content_for(folder_id)
      contents = find_by_sql("select * from folder_contents where folder_id = #{folder_id} order by seq")
      if block_given?
        contents.each{|fc| yield fc}
      else
        contents
      end
    end

    def all_pages_for(folder_id)
      contents = pages_for(folder_id)
      pages = contents.collect{|c| c.page}
      if block_given?
        pages.each{|pg| yield pg}
      else
        pages
      end
    end
    
    def has_page_id?(folder_id,pg_id)
      return false unless folder_id && pg_id
      pages_for(folder_id) do |pg|
        return true if pg.id == pg_id.to_i
      end
      return false
    end

    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    # Boolean tests
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   

    def has_contents?(folder_id)
      return false if folder_id.nil?
      find_by_sql("select  * from folder_contents where folder_id = #{folder_id}").length > 0
    end

    private
      def pages_for(folder_id)
        rvalue = find_by_sql("select * from folder_contents where folder_id = #{folder_id} and page_id is not null order by seq")
        sub_level_folders_for(folder_id) do |slf|
          pages_for(slf.id).each{|pgf| rvalue << pgf}
        end
        rvalue
      end
  end #end class methods
end
